import sys
import os
import logging
from flask import Flask, request, jsonify, send_file
from flask_cors import CORS
import json
import uuid
from datetime import datetime
from PIL import Image, ImageDraw, ImageFont
import re
import requests
import base64
from io import BytesIO
import time
from zhipuai import ZhipuAI

# 处理打包后的路径问题
if getattr(sys, 'frozen', False):
    # 打包后的环境
    base_path = sys._MEIPASS
    PROJECT_ROOT = os.path.dirname(base_path)
else:
    # 开发环境
    PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# 确保图片目录存在
IMAGE_DIR = os.path.join(PROJECT_ROOT, 'backend', 'static', 'images')
os.makedirs(IMAGE_DIR, exist_ok=True)

# 加载环境变量
from dotenv import load_dotenv
load_dotenv()

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = Flask(__name__)

@app.after_request
def after_request(response):
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
    response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
    return response

# 项目路径配置
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
IMAGE_DIR = os.path.join(PROJECT_ROOT, 'backend', 'static', 'images')
os.makedirs(IMAGE_DIR, exist_ok=True)

# 阿里云通义千问配置
ALIYUN_API_KEY = os.getenv('ALIYUN_ACCESS_KEY')
ALIYUN_API_URL = 'https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation'

# GLM-4配置
GLM4_API_KEY = os.getenv('GLM4_KEY')
glm4_client = None
if GLM4_API_KEY:
    glm4_client = ZhipuAI(api_key=GLM4_API_KEY)

logger.info(f"阿里云Qwen-image API: {'✅ 已配置' if ALIYUN_API_KEY else '❌ 未配置'}")
logger.info(f"GLM-4 API: {'✅ 已配置' if GLM4_API_KEY else '❌ 未配置'}")

def _split_into_panels_with_glm(scene_text):
    """使用GLM-4 API智能拆分文本为漫画面板"""
    if not glm4_client:
        logger.warning("GLM-4客户端未配置，使用基础拆分方法")
        return _split_into_panels_basic(scene_text)
    
    try:
        system_prompt = """你是一个专业的漫画脚本分析师。你的任务是将小说文本拆分成适合漫画表现的多个视觉面板。

请遵循以下规则：
1. 将文本按视觉场景的自然转换点拆分为2-8个面板
2. 每个面板描述应该简洁明了，专注于一个主要的视觉元素
3. 描述应该包含：场景、人物、动作、关键物体
4. 保持描述特别是人物的连续性
5. 每个描述不超过40个字符
6. 输出格式为JSON数组，每个元素包含description字段

示例输入："艾拉仿佛置身于一片由星辰构筑的森林。四周是无数漂浮、旋转的记忆碎片，它们像水晶一样折射着过往的光辉。此刻，她正跪在一块最为巨大的碎片上。碎片中，一个温馨的家庭晚餐场景正被墨汁般的黑暗吞噬。"

示例输出：
[
  {"description": "艾拉站在星辰森林中，周围漂浮记忆碎片"},
  {"description": "艾拉跪在巨大碎片上，碎片显示家庭晚餐"},
  {"description": "家庭晚餐被黑暗吞噬，人们表情扭曲"}
]

现在请处理以下文本："""
        
        response = glm4_client.chat.completions.create(
            model="glm-4-plus",
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": scene_text}
            ],
            temperature=0.7,
            max_tokens=500
        )
        
        result_text = response.choices[0].message.content.strip()
        
        # 尝试解析JSON响应
        try:
            # 清理响应文本，提取JSON部分
            json_match = re.search(r'\[.*\]', result_text, re.DOTALL)
            if json_match:
                json_str = json_match.group()
                panels_data = json.loads(json_str)
                
                # 验证数据结构
                if isinstance(panels_data, list) and len(panels_data) > 0:
                    panels = []
                    for i, panel_data in enumerate(panels_data):
                        if isinstance(panel_data, dict) and 'description' in panel_data:
                            panels.append({
                                "description": panel_data['description'],
                                "original_sentence": scene_text,  # 保留原始文本用于对话提取
                                "panel_number": i + 1
                            })
                    
                    if panels:
                        logger.info(f"GLM-4成功拆分出 {len(panels)} 个面板")
                        return panels
        except json.JSONDecodeError as e:
            logger.warning(f"GLM-4响应JSON解析失败: {e}, 响应内容: {result_text}")
        
        # 如果JSON解析失败，尝试从文本中提取面板描述
        lines = result_text.split('\n')
        panels = []
        for i, line in enumerate(lines):
            line = line.strip()
            # 匹配"面板X: 描述"或"- 描述"等格式
            match = re.search(r'(?:面板\s*\d+[:：]?\s*|[-•]\s*)(.+)', line)
            if match:
                description = match.group(1).strip()
                if len(description) > 5 and len(description) < 100:
                    panels.append({
                        "description": description,
                        "original_sentence": scene_text,
                        "panel_number": i + 1
                    })
        
        if panels:
            logger.info(f"从GLM-4响应中提取出 {len(panels)} 个面板")
            return panels[:6]  # 限制最多4个面板
        
        # 如果所有方法都失败，回退到基础拆分
        logger.warning("GLM-4响应格式不符合预期，使用基础拆分")
        return _split_into_panels_basic(scene_text)
        
    except Exception as e:
        logger.error(f"GLM-4 API调用失败: {str(e)}")
        return _split_into_panels_basic(scene_text)

def _split_into_panels_basic(scene_text):
    """基础文本拆分方法（备用）"""
    panels = []
    
    # 简单的句子分割
    sentences = re.split(r'[。！？!?；;，,]', scene_text)
    sentences = [s.strip() for s in sentences if len(s.strip()) > 5]
    
    for i, sentence in enumerate(sentences[:6]):  # 最多4个面板
        # 简化描述
        simplified = sentence[:50].replace('"', '').replace('"', '').replace('"', '')
        if len(simplified) > 10:
            panels.append({
                "description": simplified + ("..." if len(sentence) > 50 else ""),
                "original_sentence": sentence,
                "panel_number": i + 1
            })
    
    # 如果拆分失败，至少保证有一个面板
    if not panels:
        panels.append({
            "description": scene_text[:50] + "...",
            "original_sentence": scene_text,
            "panel_number": 1
        })
    
    return panels

def _extract_dialogue(text):
    """从文本中提取对话"""
    dialogues = re.findall(r'["「](.*?)["」]', text)
    return dialogues if dialogues else []

def _build_comic_prompt(panel_description, style, scene_number, panel_number, total_panels, character_consistency=""):
    """为单个面板构建专业的漫画生成提示词"""
    
    # 详细的漫画风格描述
    style_descriptions = {
        'manga': "日式漫画风格，赛璐璐上色，动态分镜，细致的线条",
        'manhua': "中国漫画风格，色彩丰富，精致的背景，唯美的画面，中式美学，彩色",
        'webtoon': "韩国网络条漫风格，竖版构图，现代感设计，鲜艳色彩，适合移动端阅读",
        'american': "美式漫画风格，粗犷线条，强烈对比，戏剧性构图，超级英雄风格，彩色"
    }
    
    style_desc = style_descriptions.get(style, "专业的漫画风格")
    
    # 构建连续性描述
    continuity = f"这是连续漫画的第{scene_number}个场景的第{panel_number}个分镜"
    
    # 角色一致性提示
    consistency_hint = f"{character_consistency}，" if character_consistency else ""
    
    # 构建完整提示词
    prompt = f"{style_desc}。{continuity}。{consistency_hint}{panel_description}。高质量漫画艺术，清晰的构图，干净的画面，不要水印。"
    
    # 确保提示词长度合适（阿里云限制800字符）
    if len(prompt) > 700:
        prompt = prompt[:690] + "。"
    
    return prompt.strip()

def _generate_with_aliyun(prompt, style):
    """使用阿里云Qwen-image生成图片"""
    try:
        if not ALIYUN_API_KEY:
            raise Exception("阿里云API密钥未配置")
        
        # 根据风格选择尺寸
        style_sizes = {
            'manga': "1328*1328",      # 1:1 适合日漫
            'manhua': "1328*1328",     # 1:1 适合中漫
            'webtoon': "928*1664",     # 9:16 适合竖版条漫
            'american': "1328*1328"    # 1:1 适合美漫
        }
        
        size = style_sizes.get(style, "1328*1328")
        
        # 构建请求数据
        data = {
            "model": "qwen-image-plus",
            "input": {
                "messages": [
                    {
                        "role": "user",
                        "content": [
                            {
                                "text": prompt
                            }
                        ]
                    }
                ]
            },
            "parameters": {
                "negative_prompt": "低分辨率，模糊，扭曲，畸形，多余的手指，错误的解剖结构，水印，文字",
                "size": size,
                "n": 1,
                "prompt_extend": False,  # 关闭智能改写以保持控制
                "watermark": False       # 不添加水印
            }
        }
        
        headers = {
            'Content-Type': 'application/json',
            'Authorization': f'Bearer {ALIYUN_API_KEY}'
        }
        
        logger.info(f"调用阿里云API，提示词长度: {len(prompt)}")
        logger.info(f"提示词预览: {prompt[:100]}...")
        
        response = requests.post(ALIYUN_API_URL, headers=headers, json=data, timeout=60)
        
        if response.status_code == 200:
            result = response.json()
            
            if 'output' in result and 'choices' in result['output']:
                image_url = result['output']['choices'][0]['message']['content'][0]['image']
                logger.info("图片生成成功，下载中...")
                
                # 下载图片
                img_response = requests.get(image_url, timeout=60)
                image = Image.open(BytesIO(img_response.content))
                
                # 调整尺寸用于漫画展示
                target_size = (800, 600) if style != 'webtoon' else (600, 800)
                image = image.resize(target_size, Image.Resampling.LANCZOS)
                
                return image
            else:
                error_msg = result.get('message', '未知错误')
                raise Exception(f"阿里云API返回错误: {error_msg}")
        else:
            error_msg = f"API调用失败: {response.status_code} - {response.text}"
            logger.error(error_msg)
            raise Exception(error_msg)
            
    except Exception as e:
        logger.error(f"阿里云图片生成失败: {str(e)}")
        raise e

def _create_comic_panel_with_aliyun(panel_description, scene_number, panel_number, total_panels, style, character_name=""):
    """使用阿里云为单个面板生成高质量漫画图片"""
    try:
        # 构建角色一致性提示
        character_consistency = f"主要角色{character_name}" if character_name else ""
        
        # 构建专业的漫画提示词
        prompt = _build_comic_prompt(panel_description, style, scene_number, panel_number, total_panels, character_consistency)
        
        logger.info(f"生成面板 {scene_number}-{panel_number}: {panel_description}")
        
        return _generate_with_aliyun(prompt, style)
            
    except Exception as e:
        logger.error(f"阿里云图片生成失败: {str(e)}")
        return _create_enhanced_comic_panel(panel_description, scene_number, panel_number, total_panels, style)

def _create_enhanced_comic_panel(panel_description, scene_number, panel_number, total_panels, style):
    """创建增强版漫画面板图片（备选方案）"""
    try:
        img = Image.new('RGB', (600, 400), color='white')
        draw = ImageDraw.Draw(img)
        
        # 尝试加载中文字体
        try:
            font_large = ImageFont.truetype("simhei.ttf", 20)
            font_medium = ImageFont.truetype("simhei.ttf", 16)
            font_small = ImageFont.truetype("simhei.ttf", 12)
        except:
            font_large = ImageFont.load_default()
            font_medium = ImageFont.load_default()
            font_small = ImageFont.load_default()
        
        # 颜色方案
        colors = {
            'manga': {'primary': '#2c3e50', 'accent': '#34495e', 'bg': '#f8f9fa'},
            'manhua': {'primary': '#c62f2f', 'accent': '#e74c3c', 'bg': '#fffaf0'},
            'webtoon': {'primary': '#2980b9', 'accent': '#3498db', 'bg': '#f0f8ff'},
            'american': {'primary': '#d35400', 'accent': '#e67e22', 'bg': '#fff8dc'}
        }.get(style, {'primary': '#2c3e50', 'accent': '#34495e', 'bg': '#f8f9fa'})
        
        # 绘制背景和边框
        draw.rectangle([0, 0, 600, 400], fill=colors['bg'])
        draw.rectangle([5, 5, 595, 395], outline=colors['primary'], width=2)
        
        # 面板标题
        title_bg = [10, 10, 590, 40]
        draw.rectangle(title_bg, fill=colors['primary'])
        draw.text((300, 25), f"场景{scene_number}-分镜{panel_number}/{total_panels}", 
                 fill='white', font=font_medium, anchor='mm')
        
        # 面板描述区域
        desc_bg = [20, 50, 580, 150]
        draw.rectangle(desc_bg, fill='white', outline=colors['accent'], width=1)
        draw.text((30, 60), "📝 面板描述", fill=colors['primary'], font=font_small)
        
        # 面板描述文本
        text_lines = _wrap_text(panel_description, 35)
        for i, line in enumerate(text_lines[:4]):
            draw.text((40, 85 + i*20), line, fill='#333', font=font_small)
        
        # 漫画预览区域
        preview_bg = [50, 170, 550, 350]
        draw.rectangle(preview_bg, fill='white', outline=colors['primary'], width=1)
        
        # 简单的漫画元素示意
        draw.ellipse([200, 200, 400, 300], outline=colors['accent'], width=2)  # 头部
        draw.line([300, 300, 300, 350], fill=colors['accent'], width=2)  # 身体
        draw.line([250, 320, 350, 320], fill=colors['accent'], width=2)  # 手臂
        
        # 风格标识
        draw.text((550, 380), f"✨ {style.upper()}", fill=colors['accent'], font=font_small)
        
        # 添加AI生成标识
        draw.text((50, 380), "🤖 AI生成面板", fill='#666', font=font_small)
        
        return img
        
    except Exception as e:
        logger.error(f"创建增强图片失败: {e}")
        # 简单错误图片
        img = Image.new('RGB', (600, 400), color='#ffebee')
        draw = ImageDraw.Draw(img)
        draw.text((300, 200), "🎨 面板生成中...", fill='#d32f2f', anchor='mm')
        return img

def _wrap_text(text, max_chars):
    """文本换行"""
    lines = []
    current_line = ""
    for char in text:
        if len(current_line) >= max_chars:
            lines.append(current_line)
            current_line = char
        else:
            current_line += char
    if current_line:
        lines.append(current_line)
    return lines

def _extract_main_character(scene_text):
    """从场景文本中提取主要角色名称"""
    # 使用GLM-4提取主要角色
    if glm4_client:
        try:
            response = glm4_client.chat.completions.create(
                model="glm-4-plus",
                messages=[
                    {"role": "system", "content": "请从以下文本中提取主要角色的名字。如果文本中没有明确的名字，请使用'主角'。只返回名字，不要其他内容。"},
                    {"role": "user", "content": scene_text}
                ],
                temperature=0.3,
                max_tokens=20
            )
            
            character_name = response.choices[0].message.content.strip()
            if character_name and character_name != "主角":
                logger.info(f"GLM-4提取到角色: {character_name}")
                return character_name
        except Exception as e:
            logger.warning(f"GLM-4角色提取失败: {e}")
    
    # 基础规则提取
    name_patterns = [
        r'[艾拉|小明|小红|张三|李四|王五]+',  # 常见中文名
        r'[主角|主人公|英雄|少女|少年|男人|女人]+'  # 角色描述
    ]
    
    for pattern in name_patterns:
        matches = re.findall(pattern, scene_text)
        if matches:
            return matches[0]
    
    return "主角"

# 路由函数
@app.route('/')
def serve_index():
    """服务首页"""
    try:
        if getattr(sys, 'frozen', False):
            # 打包环境 - 使用 sys._MEIPASS 中的 frontend 目录
            frontend_path = os.path.join(sys._MEIPASS, 'frontend')
            print(f"🔧 打包环境前端路径: {frontend_path}")
        else:
            # 开发环境
            frontend_path = os.path.join(PROJECT_ROOT, 'frontend')
            print(f"🔧 开发环境前端路径: {frontend_path}")
        
        index_path = os.path.join(frontend_path, 'index.html')
        print(f"📄 尝试加载首页: {index_path}")
        print(f"📄 首页文件存在: {os.path.exists(index_path)}")
        
        if os.path.exists(index_path):
            return send_file(index_path)
        else:
            # 列出目录内容帮助调试
            if os.path.exists(frontend_path):
                files = os.listdir(frontend_path)
                print(f"📁 前端目录内容: {files}")
            return jsonify({
                "status": "error",
                "message": "首页文件未找到",
                "frontend_path": frontend_path,
                "index_path": index_path,
                "files_in_frontend": files if 'files' in locals() else "目录不存在"
            }), 404
    except Exception as e:
        print(f"❌ 服务首页时出错: {e}")
        return jsonify({
            "status": "error",
            "message": f"服务首页时出错: {str(e)}"
        }), 500

@app.route('/css/<path:filename>')
def serve_css(filename):
    """服务CSS文件"""
    try:
        if getattr(sys, 'frozen', False):
            css_path = os.path.join(sys._MEIPASS, 'frontend', 'css', filename)
        else:
            css_path = os.path.join(PROJECT_ROOT, 'frontend', 'css', filename)
        
        print(f"🎨 加载CSS: {css_path}")
        if os.path.exists(css_path):
            return send_file(css_path)
        return jsonify({"error": f"CSS文件未找到: {css_path}"}), 404
    except Exception as e:
        return jsonify({"error": f"CSS服务错误: {str(e)}"}), 500

@app.route('/js/<path:filename>')
def serve_js(filename):
    """服务JS文件"""
    try:
        if getattr(sys, 'frozen', False):
            js_path = os.path.join(sys._MEIPASS, 'frontend', 'js', filename)
        else:
            js_path = os.path.join(PROJECT_ROOT, 'frontend', 'js', filename)
        
        print(f"📜 加载JS: {js_path}")
        if os.path.exists(js_path):
            return send_file(js_path)
        return jsonify({"error": f"JS文件未找到: {js_path}"}), 404
    except Exception as e:
        return jsonify({"error": f"JS服务错误: {str(e)}"}), 500

def home():
    return jsonify({
        "status": "success",
        "message": "小说转漫画服务（GLM-4+阿里云多分镜优化版）",
        "timestamp": datetime.now().isoformat(),
        "features": {
            "multi_panel": True,
            "smart_text_analysis": True,
            "character_consistency": True,
            "providers": ["GLM-4", "Aliyun Qwen-image"]
        }
    })

@app.route('/health')
def health():
    return jsonify({"status": "healthy", "service": "novel-to-comic-glm4-aliyun"})

@app.route('/api/process-novel', methods=['POST', 'OPTIONS'])
def process_novel():
    if request.method == 'OPTIONS':
        return '', 200
    
    try:
        data = request.get_json()
        text = data.get('text', '').strip()
        
        if not text or len(text) < 50:
            return jsonify({"error": "文本太短，请至少输入50个字符"}), 400
        
        # 改进的场景分割逻辑
        scenes = re.split(r'[。！？!?]\s*', text)
        scenes = [scene.strip() for scene in scenes if len(scene.strip()) > 10]
        
        # 如果场景太多，合并一些小场景
        if len(scenes) > 10:
            merged_scenes = []
            current_scene = ""
            for scene in scenes:
                if len(current_scene) + len(scene) < 300:
                    current_scene += scene + "。"
                else:
                    if current_scene:
                        merged_scenes.append(current_scene)
                    current_scene = scene + "。"
            if current_scene:
                merged_scenes.append(current_scene)
            scenes = merged_scenes
        
        processed_scenes = []
        for i, scene_text in enumerate(scenes):
            # 使用GLM-4为每个场景拆分多个面板
            panels = _split_into_panels_with_glm(scene_text)
            main_character = _extract_main_character(scene_text)
            
            processed_scenes.append({
                "scene_number": i + 1,
                "original_text": scene_text,
                "panels": panels,
                "main_character": main_character,
                "total_panels": len(panels)
            })
        
        return jsonify({
            "status": "success",
            "scenes": processed_scenes,
            "total_scenes": len(processed_scenes)
        })
        
    except Exception as e:
        logger.error(f"处理小说时出错: {str(e)}")
        return jsonify({"error": f"处理失败: {str(e)}"}), 500

@app.route('/api/generate-comic', methods=['POST', 'OPTIONS'])
def generate_comic():
    if request.method == 'OPTIONS':
        return '', 200
    
    try:
        data = request.get_json()
        scenes = data.get('scenes', [])
        style = data.get('style', 'manga')
        total_scenes = len(scenes)
        
        if not scenes:
            return jsonify({"error": "没有场景数据"}), 400
        
        comic_pages = []
        
        for scene in scenes:
            scene_number = scene.get('scene_number', 1)
            panels_data = scene.get('panels', [])
            main_character = scene.get('main_character', '主角')
            total_panels = len(panels_data)
            
            page_panels = []
            
            for panel_index, panel in enumerate(panels_data):
                panel_description = panel.get('description', '')
                original_sentence = panel.get('original_sentence', '')
                
                # 为每个面板生成图片
                img = _create_comic_panel_with_aliyun(
                    panel_description, 
                    scene_number, 
                    panel_index + 1, 
                    total_panels, 
                    style, 
                    main_character
                )
                
                panel_id = str(uuid.uuid4())
                image_filename = f"{panel_id}.png"
                image_path = os.path.join(IMAGE_DIR, image_filename)
                img.save(image_path, 'PNG', quality=95)
                
                # 提取该面板的对话
                panel_dialogues = _extract_dialogue(original_sentence)
                dialogue = panel_dialogues[0] if panel_dialogues else ""
                
                page_panels.append({
                    "panel_id": panel_id,
                    "description": panel_description,
                    "original_sentence": original_sentence,
                    "image_path": panel_id,
                    "dialogue": dialogue,
                    "panel_number": panel_index + 1
                })
                
                # 添加延迟避免API限流
                logger.info(f"完成面板 {scene_number}-{panel_index + 1}，等待2秒...")
                time.sleep(2)
            
            page_data = {
                "page_id": str(uuid.uuid4()),
                "scene_number": scene_number,
                "original_text": scene.get('original_text', ''),
                "panels": page_panels,
                "style": style,
                "timestamp": datetime.now().isoformat(),
                "total_panels": total_panels,
                "main_character": main_character
            }
            
            comic_pages.append(page_data)
            
            logger.info(f"完成场景 {scene_number}，包含 {total_panels} 个面板")
        
        return jsonify({
            "status": "success",
            "pages": comic_pages,
            "total_pages": len(comic_pages),
            "features_used": ["smart_text_analysis", "multi_panel", "character_consistency"],
            "providers": ["GLM-4", "Aliyun Qwen-image-plus"]
        })
        
    except Exception as e:
        logger.error(f"生成漫画时出错: {str(e)}")
        return jsonify({"error": f"生成失败: {str(e)}"}), 500

@app.route('/api/get-comic-page/<page_id>')
def get_comic_page(page_id):
    try:
        image_path = os.path.join(IMAGE_DIR, f"{page_id}.png")
        if os.path.exists(image_path):
            return send_file(image_path, mimetype='image/png')
        else:
            return jsonify({"error": "图片未找到"}), 404
    except Exception as e:
        logger.error(f"获取漫画页面时出错: {str(e)}")
        return jsonify({"error": str(e)}), 500

@app.route('/api/debug/ai-test')
def debug_ai_test():
    """测试AI服务连接"""
    results = {}
    
    # 测试GLM-4
    if GLM4_API_KEY:
        try:
            response = glm4_client.chat.completions.create(
                model="glm-4-plus",
                messages=[
                    {"role": "system", "content": "你是一个测试助手，请回复'服务正常'"},
                    {"role": "user", "content": "你好"}
                ],
                max_tokens=10
            )
            results["glm4"] = {
                "status": "success",
                "response": response.choices[0].message.content
            }
        except Exception as e:
            results["glm4"] = {
                "status": "error",
                "error": str(e)
            }
    else:
        results["glm4"] = {
            "status": "not_configured"
        }
    
    # 测试阿里云
    if ALIYUN_API_KEY:
        try:
            test_prompt = "测试图片，一个简单的红色圆形"
            data = {
                "model": "qwen-image-plus",
                "input": {
                    "messages": [
                        {
                            "role": "user",
                            "content": [
                                {
                                    "text": test_prompt
                                }
                            ]
                        }
                    ]
                },
                "parameters": {
                    "size": "1328*1328",
                    "n": 1,
                    "prompt_extend": False,
                    "watermark": False
                }
            }
            
            headers = {
                'Content-Type': 'application/json',
                'Authorization': f'Bearer {ALIYUN_API_KEY}'
            }
            
            response = requests.post(ALIYUN_API_URL, headers=headers, json=data, timeout=30)
            
            if response.status_code == 200:
                result = response.json()
                if 'output' in result:
                    results["aliyun"] = {
                        "status": "success",
                        "task_id": "测试任务提交成功"
                    }
                else:
                    results["aliyun"] = {
                        "status": "error",
                        "error": result.get('message', '未知错误')
                    }
            else:
                results["aliyun"] = {
                    "status": "error",
                    "http_status": response.status_code,
                    "error": response.text
                }
                
        except Exception as e:
            results["aliyun"] = {
                "status": "error",
                "error": str(e)
            }
    else:
        results["aliyun"] = {
            "status": "not_configured"
        }
    
    return jsonify(results)

if __name__ == '__main__':
    print("=" * 60)
    print("🎨 小说转漫画GLM-4+阿里云多分镜优化版服务启动中...")
    print("📡 服务地址: http://localhost:5000")
    print(f"🖼️  图片目录: {IMAGE_DIR}")
    print(f"🧠 GLM-4 API: {'✅ 已配置' if GLM4_API_KEY else '❌ 未配置'}")
    print(f"🎨 阿里云API: {'✅ 已配置' if ALIYUN_API_KEY else '❌ 未配置'}")
    print("🔄 模式: 智能多分镜生成")
    print("✨ 特性: GLM-4文本分析、多面板分镜、角色一致性")
    print("🤖 模型: glm-4-plus + qwen-image-plus")
    print("=" * 60)
    
    # 测试AI服务连接
    print("🧪 测试AI服务连接...")
    try:
        with app.test_client() as client:
            response = client.get('/api/debug/ai-test')
            data = response.get_json()
            
            if data.get("glm4", {}).get("status") == "success":
                print("✅ GLM-4 API连接测试成功")
            else:
                print(f"❌ GLM-4 API连接测试失败: {data.get('glm4', {}).get('error', '未配置')}")
            
            if data.get("aliyun", {}).get("status") == "success":
                print("✅ 阿里云API连接测试成功")
            else:
                print(f"❌ 阿里云API连接测试失败: {data.get('aliyun', {}).get('error', '未配置')}")
    except Exception as e:
        print(f"❌ AI服务测试异常: {e}")
    
    app.run(debug=True, host='0.0.0.0', port=5000, use_reloader=False)